package com.lkm.app_ui.m.Imple.order_img;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;

import com.lkm.app_ui.AppConfig;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.event.OnSubtotalRealEvent;
import com.lkm.app_ui.log.AppLogger;
import com.lkm.app_ui.m.camera.CameraModule;
import com.lkm.app_ui.m.fun.OnWeightHoldEvent;
import com.lkm.app_ui.m.order_img.OrderImgModule;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusEventFlag;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.OnOrderAddEvent;
import com.lkm.market2_0.m.steelyardserver.event.OnWeightInfoChangeEvent;
import com.lkm.market2_0.m.steelyardserver.to.WeightChangeInfo;



public class OrderImgModuleImpl implements OrderImgModule {

    private CameraHandler handler;
    private static final int SLIENT_TACK_CAMERA = 1;
    private static final int SLIENT_CLOSE_CAMERA = 2;

    public OrderImgModuleImpl(CameraModule cameraModule) {
        handler = new CameraHandler(cameraModule);
        reOnSubtotalRealEvent();
        reOnOrderAddEvent();


        
        UpImageTask.tryUp();
    }

    
    private void reOnOrderAddEvent() {
        LinkBus.registerReceiver(new ObserverAutoNext<OnOrderAddEvent>() {
            @Override
            public void onReceiver(OnOrderAddEvent data) {
                
                if (AppConfig.isOrderImgTack())
                    if (data.getOrderEntity().type == OrderEntity.TYPE_Full1 || (data.getOrderEntity().type == OrderEntity.TYPE_NotFull0 && !StringHelp.isEmpty(data.getOrderEntity().orderNum))) {
//                    if(data.getOrderEntity().type == OrderEntity.TYPE_Full1){
                        ImgFiler.ayncCpToUp(data.getOrderEntity(), new Runnable() {
                            @Override
                            public void run() {
                                if (AppConfig.isOrderImgToMe) {
                                    UpImageTask.tryUp();
                                }
                            }
                        });

                    }

            }

            @Override
            public Class getBusEventClass() {
                return OnOrderAddEvent.class;
            }
        });
    }

    @Override
    public void requestTackImg(OrderEntity.GoodEntity goodEntity, boolean ishold) {
        handler.sendMessage(handler.obtainMessage(SLIENT_TACK_CAMERA, new Object[]{goodEntity, ishold}));
    }

    
    private void reOnSubtotalRealEvent() {
        LinkBus.registerReceiver(new ObserverAutoNext<OnSubtotalRealEvent>() {
            @Override
            public void onReceiver(OnSubtotalRealEvent data) {
                OrderEntity.GoodEntity[] realGoods = data.getRealGoods();
                
                if (CollectionHelp.isEmpty(realGoods)) {
                    ImgFiler.ayncDeleteAllTemp();
                } else if (data.isAdd()) {
                    OrderEntity.GoodEntity[] changeGoods = data.getChangeGoods();
                    for (int i = 0; i < changeGoods.length; i++) {
                        OrderEntity.GoodEntity goodEntity = changeGoods[i];
                        handler.sendMessage(handler.obtainMessage(SLIENT_TACK_CAMERA, new Object[]{goodEntity, true}));
                    }
                } else {
                    
                    OrderEntity.GoodEntity[] changeGoods = data.getChangeGoods();
                    for (int i = 0; i < changeGoods.length; i++) {
                        ImgFiler.ayncDeleteTemp(changeGoods[i]);
                    }
                }

            }

            @Override
            public Class getBusEventClass() {
                return OnSubtotalRealEvent.class;
            }
        });
    }



    
    private void reOnWeightInfoChangeEvent() {
        LinkBus.registerReceiver(new ObserverAutoNext<OnWeightInfoChangeEvent>() {
            @Override
            public Class<OnWeightInfoChangeEvent> getBusEventClass() {
                return OnWeightInfoChangeEvent.class;
            }

            private double preHoldWeight = 0;
            private double holdWeight = 0;

            private double preweight = 0;
            private long preChanerTime = 0;


            @Override
            public void onReceiver(OnWeightInfoChangeEvent data) {
                WeightChangeInfo weightChangeInfo = data.getWeightChangeInfo();

                boolean isHold = false;

                double curWeight = weightChangeInfo.getWeight();


                

                if (preweight != curWeight) {
                    preweight = curWeight;
                    preChanerTime = SystemClock.uptimeMillis();
                } else {
                    
                    if (SystemClock.uptimeMillis() - preChanerTime > 700) {
                        isHold = true;
                        preHoldWeight = holdWeight;
                        holdWeight = curWeight;
                    }
                }

                if (isHold) {
                    
                    if (curWeight - preHoldWeight > 0.05) {
                        

                        OrderEntity.GoodEntity goodEntity = new OrderEntity.GoodEntity("isShow == true","",0,0,"",0,0,0,0,0, new OrderEntity.GoodEntityEx());
                        handler.sendMessage(handler.obtainMessage(SLIENT_TACK_CAMERA, new Object[]{goodEntity, true}));

                    }


                }


            }
        });
    }


    private static class CameraHandler extends Handler {
        CameraModule cameraModule;


        
        Boolean preGoodEntityIshold = null;
        
        volatile OrderEntity.GoodEntity preGoodEntity = null;

        CameraHandler(CameraModule cameraModule) {
            super(Looper.getMainLooper());
            this.cameraModule = cameraModule;
        }

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SLIENT_TACK_CAMERA:
                    if (!AppConfig.isOrderImgTack()) return;

                    if (!cameraModule.isOpen()) {
                        cameraModule.open();
                    }
                    if (cameraModule.isOpen()) {
                        OrderEntity.GoodEntity goodEntity_ = (OrderEntity.GoodEntity) ((Object[]) msg.obj)[0];
                        boolean isHold_ = (boolean) ((Object[]) msg.obj)[1];


                        AppLogger.Order.tackPictureStart();

                        int status = cameraModule.tackPicture(new RunnablePR<byte[], Void>() {
                            @Override
                            public Void run(byte[] data) {
                                AppLogger.Order.tackPictureOk();
                                OrderEntity.GoodEntity goodEntity = preGoodEntity;
                                preGoodEntity = null;
                                if (data == null || goodEntity == null) return null;
                                ImgFiler.ayncSave(goodEntity, data);
                                return null;
                            }
                        });
                        if (status == 0) {
                            
                            preGoodEntityIshold = isHold_;
                            preGoodEntity = goodEntity_;
                        } else if (status == 2) {

                            
                            if (preGoodEntityIshold != null)
                                if (!preGoodEntityIshold && preGoodEntity != null) {
                                    preGoodEntity = goodEntity_;
                                    preGoodEntityIshold = isHold_;
                                }
                        }
                        AppLogger.Order.tackPictureIng();

                    }
                    break;
                case SLIENT_CLOSE_CAMERA: {
                    cameraModule.close();
                }
                break;
                default:
                    break;
            }
        }
    }

}
